import { Button, Form, FormInstance, Input, Modal, Pagination, Select, Table, message } from 'antd'
import React, { useEffect, useState } from 'react'

import * as common from './../../../api/common';
import * as courseSet from '../../../api/course/set';
import { SearchType } from '../../../api/course/set';
import useBseGeneraHook from '../../../components/BaseGeneraForm/hook';
import { BaseGeneraForm } from '../../../components';

const CourseSet: React.FC = () => {
  const [formDataConfig, setFormDataConfig] = useState<any[]>([
    {
      type: 'Input',
      label: '课程名称',
      fieldName: 'name',
      placeholder: '请输入',
      rules: [{ required: true, message: '请输入课程名' }]
    },
    {
      type: 'InputNumber',
      label: '课程学分',
      fieldName: 'credit',
      placeholder: '请输入学分',
      rules: [{ required: true, message: '请输入学分' }]
    },
    {
      type: 'InputNumber',
      label: '课程人数',
      fieldName: 'realityPeopleNumber',
      placeholder: '请输入人数',
      rules: [{ required: true, message: '请输入人数' }]
    },
    {
      type: 'Select',
      label: '教师',
      fieldName: 'teacher_id',
      placeholder: '请选择教师',
      rules: [{ required: true, message: '请选择教师' }],
      child: []
    },
    {
      type: 'Select',
      label: '专业',
      fieldName: 'major_id',
      placeholder: '请选择专业',
      rules: [{ required: true, message: '请选择专业' }],
      child: []
    },
    {
      type: 'TextArea',
      label: '课程描述',
      fieldName: 'desc',
      placeholder: '描述'
    },
    {
      type: 'Select',
      label: '课程属性',
      fieldName: 'attribute',
      placeholder: '请选择课程属性',
      rules: [{ required: true, message: '请选择课程属性' }],
      child: [{
        label: '公共课',
        key: '公共课',
        value: '公共课'
      }, {
        label: '专业课',
        key: '专业课',
        value: '专业课'
      }]
    }
  ])
  const { open, edit, rowId, openModal, closeModal, addModal, editModal, rowIdSelect, formRef } = useBseGeneraHook()
  const [teacher, setTeacher] = useState<any[]>([])
  const [formData, setFormData] = useState<any>()
  const [major, setMajor] = useState<any[]>([])
  const [list, setList] = useState<any[]>([])
  const [total, setTotal] = useState<number>(0)
  const [search, setSearch] = useState<SearchType>({ limit: 10, page: 1 })


  const getTeacherList = async () => {
    const res = await common.teacherList().catch(err => console.log(err))
    formDataConfig.forEach(item => {
      if (item.fieldName == 'teacher_id') {
        item.child = res.data
      }
    })
    setTeacher(res.data)
  }
  const getMajorList = async () => {
    const res = await common.majorList().catch(err => console.log(err))
    formDataConfig.forEach(item => {
      if (item.fieldName == 'major_id') {
        item.child = res.data
      }
    })
    setMajor(res.data)
  }

  const getList = async () => {
    const res = await courseSet.courseList(search).catch(err => console.log(err))
    setList(res.data.content)
    setTotal(res.data.totalElements)
  }


  useEffect(() => {
    getTeacherList()
    getMajorList()
  }, [])

  useEffect(() => {
    getList()
  }, [search])

  const onFinish = (value: any) => {
    setSearch(value)
  }
  const reset = () => {
    setSearch({ limit: 10, page: 1, teacher_id: null, major_id: null, name: null, attribute: null })
    formRef.current?.resetFields();
  }

  const add = () => {
    openModal()
    addModal()
  }
  const rowEdit = (record: any) => {
    openModal()
    editModal()
    rowIdSelect(record.id)
    setFormData(record)
    console.log(record)
  }
  const del = async (val: any) => {
    Modal.confirm({
      title: '确定删除',
      icon: null,
      okText: '是',
      cancelText: '否',
      onOk() {
        courseSet.courseDel(val.id).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const emitOnFinish = async (value: any, isAdd: boolean) => {
    let res = ''
    if (isAdd) {
      res = await courseSet.courseCreated(value).catch(err => console.log(err))
    } else {
      res = await courseSet.courseUp(rowId, value).catch(err => console.log(err))
    }
    if (res.success) {
      isAdd ? message.success('添加成功') : message.success('更新成功')
      getList()
      closeModal()
    }
  }
  const onChange = (page: number, pageSize: number) => {
    setSearch({ ...search, page: page || 1, limit: pageSize })
  }
  return (
    <>
      <div>
        <Form layout='inline' onFinish={onFinish} ref={formRef}>
          <Form.Item label="课程名" name="name">
            <Input placeholder="课程名" allowClear />
          </Form.Item>
          <Form.Item label="课程属性" name="attribute">
            <Select style={{ width: '100px' }} allowClear>
              {
                ['专业课', '公共课'].map(c => {
                  return <Select.Option value={c} key={c}>{c}</Select.Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item label="教师" name="teacher_id">
            <Select style={{ width: '100px' }} allowClear>
              {
                teacher.map(c => {
                  return <Select.Option value={c.value} key={c.value}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>

          <Form.Item label="专业" name="major_id">
            <Select style={{ width: '100px' }} allowClear>
              {
                major.map(c => {
                  return <Select.Option value={c.value} key={c.id}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>

          <Form.Item >
            <Button type="primary" htmlType="submit">搜索</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="primary" onClick={add}>添加</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="dashed" onClick={reset}>重置</Button>
          </Form.Item>
        </Form>
      </div >
      <div>
        <Table dataSource={list} pagination={false} rowKey="id"
          columns={[
            {
              title: '课程名',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '课程属性',
              dataIndex: 'attribute',
              key: 'attribute',
            },
            {
              title: '学分',
              dataIndex: 'credit',
              key: 'credit',
            },
            {
              title: '人数',
              dataIndex: 'realityPeopleNumber',
              key: 'realityPeopleNumber',
            },
            {
              title: '授课老师',
              key: 'option1',
              render: (_: any, record: any) => (
                <><span>{record.teacher.t_name}</span></>
              ),
            },
            {
              title: '操作',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <Button type="primary" onClick={() => rowEdit(record)}>编辑</Button>
                  <>&nbsp;</>
                  <Button type="primary" onClick={() => del(record)}>删除</Button>
                </>
              ),
            },
          ]}
        />
      </div>
      <div><Pagination showSizeChanger={true} total={total} onChange={onChange} /></div>

      <BaseGeneraForm
        title={edit ? '创建课程' : '查看课程'}
        open={open}
        isAdd={edit}
        footer={null}
        formData={formData}
        formDataConfig={formDataConfig}
        emitOnFinish={emitOnFinish}
        onCancel={closeModal} />
    </>
  )
}

export default CourseSet
